from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework import status
from rest_framework.decorators import action

from apps.meiduo_admin.serializers.order import OrderInfoSerializer
from apps.meiduo_admin.utils import PageNum
from apps.orders.models import OrderInfo


class OrderModelViewSet(ModelViewSet):
    """
    订单管理-订单获取
    """

    # 指定查询集
    # queryset = OrderInfo.objects.all()

    # 实现搜索重写get_queryset
    def get_queryset(self):
        keyword = self.request.query_params.get("keyword")
        if keyword:
            return OrderInfo.objects.filter(order_id__contains=keyword)
        else:
            return OrderInfo.objects.all()

    # 指定序列化器
    serializer_class = OrderInfoSerializer

    # 指定分页器
    pagination_class = PageNum

    def destroy(self, request, *args, **kwargs):
        """
        重写destroy,不删除订单,订单是商家和用户的依据
        """
        return Response(status=403)

    # lookup_field 默认是pk,如果想改就重新赋值
    # lookup_field = pk
    # method 请求方法,默认get
    # detail=True表示在指定视图后跟函数名,
    # detail=False表示在列表视图后跟函数名,
    @action(methods=["put"],detail=True)
    def status(self,request,pk):
        """
        修改订单
        :param request:
        :param pk:
        :return:
        """
        # 1. 获取指定订单信息
        # 方法一:
        order = self.get_object()
        # 方法二:
        # order = OrderInfo.objects.get(id=pk)
        # 2. 获取请求参数
        status = request.data.get("status")
        # 3. 判断是否在订单状态中
        if status not in [OrderInfo.ORDER_STATUS_ENUM["UNPAID"],
                          OrderInfo.ORDER_STATUS_ENUM["UNSEND"],
                          OrderInfo.ORDER_STATUS_ENUM["UNRECEIVED"],
                          OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"],
                          OrderInfo.ORDER_STATUS_ENUM["FINISHED"],]:
            return Response({"error":"订单信息错误"},status=400)
        # 4. 更新数据
        order.status = status
        order.save()
        # 5. 返回响应
        return Response({
            "order_id":order.order_id,
            "status":order.status
        })

